﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Super.Common.Validate;
using Super.DomainService;
using Super.Entities;
using Super.Infrastructure;
using Super.Mvc;
using Super.Mvc.Form;

namespace Super.Web.Areas.Admin.Controllers
{
    public class ProductCategoryController : BaseController
    {
        //
        // GET: /Admin/ProductCategory/

        public ActionResult Index()
        {
            var page = Query.Params("pageNum");
            if (string.IsNullOrEmpty(page))
            {
                page = "1";
            }
            var adp = new DbContextAdapter();
            var productCategoryService = new ProductCategoryService(adp);
            var categoryList =
                productCategoryService.Repository.Find(a => a.IsDel == false).OrderBy(a=>a.Sort).Page(page.ToInt(), PageSize);
            BindPage(categoryList.ItemCount, page.ToInt(), PageSize);
            return View(categoryList.ItemCollection.ToList());
        }

        public ActionResult Edit()
        {
            var pid = Query.Get("pid").ToInt(0);
            if (pid > 0)
            {
                var adp = new DbContextAdapter();
                var categoryService = new ProductCategoryService(adp);
                var categoryModel = categoryService.Repository.Find(a => a.ID == pid).FirstOrDefault();
                ViewBag.categoryModel = categoryModel;
                return View(categoryModel);
            }
            return View();
        }

        [HttpPost]
        public JsonResult Edit(ProductCategory model)
        {

            var adp = new DbContextAdapter();
            var categoryService = new ProductCategoryService(adp);
         
            categoryService.Repository.InsertOrUpdate(model);
            adp.SaveChanges();
            return JsonBack.Tip(adp.ErrorMessage, "productcategory","修改成功");

        }

        public JsonResult Delete()
        {
            var pid = Query.Get("pid").ToInt(0);
            var adp = new DbContextAdapter();
            var categoryService = new ProductCategoryService(adp);
            var categoryModel = categoryService.Repository.Find(a => a.ID == pid).FirstOrDefault();
            if (categoryModel != null)
            {
                categoryService.Repository.Delete(categoryModel,true);
            }
            adp.SaveChanges();
            return JsonBack.Tip(adp.ErrorMessage, "productcategory", "删除成功");
           
        }
    }
}
